package cn.tedu.v2;

import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * 聊天室 Version  1
 * 功能： 1.客户端--指定IP，端口号
 *       2.客户端给服务器发送文本
 *       3.客户端完成标准IO
 * 【新增】4.捕获异常，打印异常信息--异常全部抓住，用户明确提示
 *       5.关闭socket
 * 客户端
 */
public class Client {
    private Socket socket;
    public Client(){
        try {
            socket=new Socket("172.21.69.1",0202);
        } catch (UnknownHostException e) {  //用户地址出问题异常
            System.out.println("IP地址有问题，请询问服务器端！");
        } catch (IOException e) { //IO异常：连接失效，客户端主动退出了
            System.out.println("客户端主动退出了：断开链接");
        }finally {

        }
    }
    public void start() throws IOException {
        OutputStream os = null;
        OutputStreamWriter osw = null;
        BufferedWriter bw = null;
        PrintWriter pw = null;
        try {
            pw = null;
            os = socket.getOutputStream();
            osw = new OutputStreamWriter(os, "UTF8");
            bw = new BufferedWriter(osw);
            pw = new PrintWriter(bw, true);
            System.out.println("客户端用户：请输入文字：");
            Scanner input = new Scanner(System.in);  //测试--控制台输入文本
            while (true) { //死循环--一直与服务器说话
                String say = input.nextLine();
                pw.println(say);  //写出  一行行文字
                System.out.println("写出完毕");
            }
        } catch (UnsupportedEncodingException e) {
            System.out.println("客户端与服务器端：字符集不一致！");
        } catch(SocketException e) {
            System.out.println("客户端被重置了~");
        } catch (IOException e) {
            System.out.println("客户端断开链接！");
        } finally {
            if (pw != null)
                pw.close();
            try {
                socket.close();
            } catch (IOException e) {
                System.out.println("客户端离开了");
            }
        }
    }
    public static void main(String[] args) throws IOException {
        Client client=new Client();
        client.start();
    }
}
